import {
  ui
} from './ui'

const CommonRegex = {
  integer: "[\\+-]?\\d+",
  decimal: "[\\+-]?\\d+(\\.\\d+)?",
  telephone: "0\\d{2,3}-\\d{7,8}",
  mobile: "(1\\d{10})",
  email: "[A-Za-z0-9\\u4e00-\\u9fa5]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+"
}

export const checkTool = {
  /**
   * @param {*} fields [{title, value, fn, regex, allowEmpty}, ...]
   */
  check(fields) {
    let valid = true
    for (let ele of fields) {
      if (ele.allowEmpty) {
        if (this.isEmpty(ele.value)) continue
      }
      if (ele.regex) {
        const regex = new RegExp("^" + ele.regex + "$")
        valid = regex.test(ele.value)
      } else if (ele.fn) { // ele.fn
        // console.log(ele)
        valid = this.execFn(ele)
      } else {
        if (!ele.allowEmpty) valid = !(this.isEmpty(ele.value))
      }

      if (!valid) {
        ui.toast(false, (ele.title || '') + '格式错误' + (ele.tip ? '： ' + ele.tip : ''))
        throw "invalid input"
      }
    }

    return valid
  },
  isEmpty(str) {
    return str == undefined || `${str}`.trim() == ''
  },
  execFn(ele) {
    const rst = ele.fn(ele.value)
    // console.log(ele, rst)
    return rst
  },
  test(value, strRegex) {
    const regex = new RegExp("^" + strRegex + "$")
    return regex.test(value)
  },
  CommonRegex,
}